import json
import time
from newpro.db import db
from newpro.util.md5 import md5
from newpro.util.myjwt import myjwt
from newpro.util.myredis import r
from newpro.views.base import BaseHandler




class UserHandler(BaseHandler):
    def get(self):
        r.set_str("name", "abc")
        print(r.get_str("name"))
        # 获取参数
        # name = self.get_query_argument("name")
        # password = self.get_query_argument("password")
        # # self.write("name is :"+name+",password is:"+password)
        # self.write(json.dumps({"id":1}))
        self.write("34234234")

    def post(self):
        data = json.loads(self.request.body)
        id = data['id']
        name = data['name']

        self.write("name 23is post:" + str(id) + ",password is:" + name)

#通过角色id获取资源列表的方法
def getMenu(roleid):
    sql="select res.*,pres.name as pname from role_resource as rr left join resource as res on rr.resourceid=res.id  inner join resource as pres on res.pid=pres.id where rr.userid=%d and res.type=1"%(int(roleid))
    res = db.findAll(sql)

    reslist=[]
    ids=[]
    pomitonlist = []
    #遍历查询结果
    for i in res:
        pomitonlist.append(i['url'])
        #判断父类是否存在，不存在添加
        if i["pid"] not in ids:
            ids.append(i['pid'])
            reslist.append({"id":i["pid"], "name":i['pname'],"son":[{"id":i['id'],"name":i['name'],'url':i['url']}]})
        else:
            #存在，查找父类，遍历父类用子类的pid对比
            for (index,p) in enumerate(reslist):
                if i['pid'] == p['id']:
                    #将子类加到父类下
                    reslist[index]['son'].append({"id":i['id'],"name":i['name'],'url':i['url']})
    return reslist, pomitonlist

def getinterfacelist(roleid):
    sql = "select res.url from role_resource as rr inner join resource as res on rr.resourceid=res.id where rr.userid=%d and res.type=2"%(int(roleid))
    res = db.findAll(sql)
    return res

class Login(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        name = data['name']
        password = data['password']
        if not all([name, password]):
            self.finish({'code': 404, 'message': '用户名或密码未输入'})
        sql = "select * from admin_user where username='%s'"%(str(name))
        user = db.findOne(sql)
        if user:
            mdpwd = md5(password)
            if mdpwd == user['password']:
                # 生成token
                data = {"data": {"name": user['username'], "userid": user['id'], 'roleid': user['roleid'], "exp": time.time()}}
                token = myjwt.jwt_en(data)
                # 获取角色id获取资源列表的方法
                menulist,pomitonlist = getMenu(user['roleid'])
                # 通过roleid获取接口权限
                interlist = getinterfacelist(user['roleid'])
                # 存在redis
                key = "interlist" + str(user['roleid'])
                r.set_str(key, json.dumps(interlist))
                redata = {"code":200,"token":token,'name':user['name'],'id':user['id'], "pomitonlist": pomitonlist, 'mpstatus':user['mpstatus'],'roleid':user['roleid'],'menulist':menulist}
                self.finish(redata)
            else:
                self.finish({'code': 401, 'msg': '用户名或密码错误'})
        else:
            self.finish({'code': 400, 'msg': '用户名或密码错误'})

class LoginOutHandler(BaseHandler):
    def get(self):
        token = self.request.headers['token']
        key = 'logoutlist'
        r.sortedset_add(key, token, int(time.time()))
        self.finish({'code': 200})

class UploadPassword(BaseHandler):
    # 修改密码
    def post(self):
        data = json.loads(self.request.body)
        pwd = data["pwd"]
        pwds = data["pwds"]
        userid = data["id"]
        if not all([pwd, pwds, userid]):
            self.finish({"code": 400, "msg": "字段不能为空"})
        else:
            password = md5(pwd)
            sql = "select * from admin_user where id=%d" % (int(userid))
            res = db.findOne(sql)
            if res:
                if res["password"] != password:
                    self.finish({"code": 400, "msg": "旧密码错误"})
                else:
                    pwds1 = md5(pwds)
                    if pwds1 != res["password"]:
                        sql1 = "update admin_user set password='%s', mpstatus=2 where id = %d" % (pwds1, int(userid))
                        db.add(sql1)
                        db.commit()
                        self.finish({"code": 200, "msg": "修改密码成功"})
                    else:
                        self.finish({"code": 400, "msg": "新旧密码一致"})
            else:
                self.finish({"code": 400, "msg": "用户不存在"})



